const mysql = require('mysql');

// 创建连接对象
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'bs1959',
    port: 3306,
    database: 'myblog'
});

// 开始连接
connection.connect();

// 执行sql语句,查询
const sqlSelect = `select * from blogs`;
connection.query(sqlSelect, (err, result) => {
    if(err){
        console.error(err);
        return;
    }
    console.log('result', result);
});
/*
运行结果
result [
  RowDataPacket {
    id: 1,
    title: '标题3',
    content: '内容1',
    author: 'zhangsan',
    createdAt: 1234567890123,
    state: 1
  },
  RowDataPacket {
    id: 4,
    title: '标题2',
    content: '内容2',
    author: 'zhangsan',
    createdAt: 1234567890666,
    state: 0
  }
]
*/

// // 执行sql语句，添加
// const sqlSave = `insert into blogs (title, content, author, createdAt) values ('标题5','内容5', 'lisi', 1234567890111);`;
// connection.query(sqlSave, (err, result) => {
//     if(err){
//         console.error(err);
//         return;
//     }
//     console.log('result', result);
// });
/*
运行结果
result OkPacket {
  fieldCount: 0, 
  affectedRows: 1,
  insertId: 5,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}
*/

// 执行sql语句，更新
// const sqlUpdate = `update blogs set title = '标题9' where content = '内容1';`;
// connection.query(sqlUpdate,(err, result) => {
//     if(err){
//         console.error('error', err);
//         return;
//     }
//     console.log('result', result);
// });
/*
执行结果
result OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '(Rows matched: 1  Changed: 1  Warnings: 0',
  protocol41: true,
  changedRows: 1
}
*/

// 执行sql语句，删除
// const sqlDelete = `delete from blogs where title = '标题5'`;
// connection.query(sqlDelete, (err, result) => {
//     if(err){
//         console.error('error', err);
//         return;
//     }
//     console.log('result', result);
// });
/*
运行结果
result OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}
*/

// 关闭连接
connection.end();